import {Controller} from 'egg';

class NewsController extends Controller{
    /**
     * 添加新闻
     */
    public async createNews(){
        const { ctx, ctx: { request } } = this;
        try {
            ctx.validate({
                news_title: 'string',
                news_summary:'string',
                news_detail: 'string',
            }, request.body)
        } catch (e) {
            ctx.body = ctx.helper.responseErrorParam(e.errors[0].message);
            return;
        }
        await this.service.newsService.createNews(request.body);
        ctx.body = this.ctx.helper.responseSuccess('创建成功');
    }

    /**
     * 删除新闻
     */
    public async deleteNews(){
        const { ctx, ctx: { request } } = this;
        try {
            ctx.validate({
                news_id: 'string'
            }, request.body)
        } catch (e) {
            ctx.body = ctx.helper.responseErrorParam(e.errors[0].message);
            return;
        }
        await this.service.newsService.deleteNews(request.body);
        ctx.body = this.ctx.helper.responseSuccess('删除成功');
    }

    /**
     * 修改新闻
     */
    public async updateNews(){
        const { ctx, ctx: { request } } = this;
        try {
            ctx.validate({
                news_id: 'string',
                news_title: 'string',
                news_summary:'string',
                news_detail: 'string',
            }, request.body)
        } catch (e) {
            ctx.body = ctx.helper.responseErrorParam(e.errors[0].message);
            return;
        }
        await this.service.newsService.updateNews(request.body);
        ctx.body = this.ctx.helper.responseSuccess('修改成功');
    }

    /**
     * 查找新闻
     */
    public async searchNews(){
        const { ctx, ctx: { request } } = this;
        const result:any=await this.service.newsService.searchNews(request.body);
        ctx.body = this.ctx.helper.responseSuccess('查找成功',result);
    }

    /**
     * 根据Id查找新闻详情
     */
    public async searchNewsById(){
        const { ctx, ctx: { request } } = this;
        try {
            ctx.validate({
                news_id: 'string'
            }, request.body)
        } catch (e) {
            ctx.body = ctx.helper.responseErrorParam(e.errors[0].message);
            return;
        }
        const result:any=await this.service.newsService.searchNewsById(request.body);
        ctx.body = this.ctx.helper.responseSuccess('查找成功',result);
    }
}
export default NewsController;